{% load static %}

<div class="container">
    <div class="up">
        <div class="cover-name">
            <span class="cover">
                <img id="avatar" src="/static/media/{{ user.cover }}" alt="头像">
                <input type="file" id="avatarInput" accept="image/*" style="display: none;">
            </span>
            <span class="name">{{ username|capfirst }}</span>
            <span class="grade">等级：高级学员</span>
        </div>
        <div class="cheer">
            加油加油
        </div>
    </div>

    <div class="middle">
        <div class="target">
            <h3>学习目标</h3>
            <div class="user-target" id="user-target">
                <p>开始时间: <span id="target-start">{{ user.target_start_date }}</span></p>
                <p>结束时间: <span id="target-end">{{ user.target_end_date }}</span></p>
                <p>目标内容: <span id="target-content">{{ user.target }}</span></p>
            </div>
            <button class="edit-goal">设置目标</button>
        </div>

        <div class="plan">
            <h3>学习计划</h3>
            <div class="user-plan" id="user-plan">
                {{ user.plan }}
            </div>
            <button class="edit-plan">设置计划</button>
        </div>
    </div>

    <div class="down">
        <div class="stats">
            <h3>学习统计</h3>
            <p>本周学习时长：<span class="highlight">10小时</span></p>
            <p>目标完成进度趋势</p>
            <div class="progress-bar">
                <div class="progress" style="width: 40%;"></div>
            </div>
            <p>已经完成学习内容：<span class="highlight">第20单元</span></p>
        </div>
    </div>
</div>

<!-- 设置目标模态框 -->
<div id="goalModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h3>设置学习目标</h3>
        <form id="goalForm">
            <label for="target-start">开始时间:</label>
            <input type="date" id="target-start-input" name="target-start" required>
            <label for="target-end">结束时间:</label>
            <input type="date" id="target-end-input" name="target-end" required>
            <label for="target-content">目标内容:</label>
            <textarea id="target-content-input" name="target-content" rows="4" required></textarea>
            <button type="submit" class="button-user">提交</button>
        </form>
    </div>
</div>

<!-- 设置计划模态框 -->
<div id="planModal" class="modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h3>设置学习计划</h3>
        <form id="planForm">
            <label for="plan-content">计划内容:</label>
            <textarea id="plan-content-input" name="plan-content" rows="4" required></textarea>
            <button type="submit" class="button-user">提交</button>
        </form>
    </div>
</div>

<script>
document.getElementById("avatar").addEventListener("click", function() {
    document.getElementById("avatarInput").click();
});

document.getElementById("avatarInput").addEventListener("change", function(event) {
    let file = event.target.files[0];
    if (file) {
        let formData = new FormData();
        formData.append("avatar", file);

        fetch("{% url 'upload_avatar' %}", {
            method: "POST",
            body: formData,
            headers: {
                "X-CSRFToken": getCookie("csrftoken")
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.status === "success") {
                const avatarImg = document.querySelector('.cover img');
                avatarImg.src = data.avatar_url + "?t=" + new Date().getTime();
            } else {
                alert("头像上传失败！");
            }
        })
        .catch(error => console.error("Error:", error));
    }
});

// 获取模态框和按钮
const goalModal = document.getElementById("goalModal");
const planModal = document.getElementById("planModal");
const editGoalButton = document.querySelector(".edit-goal");
const editPlanButton = document.querySelector(".edit-plan");
const closeButtons = document.querySelectorAll(".close");

// 打开目标模态框
editGoalButton.addEventListener("click", () => {
    goalModal.style.display = "block";
});

// 打开计划模态框
editPlanButton.addEventListener("click", () => {
    planModal.style.display = "block";
});

// 关闭模态框
closeButtons.forEach(button => {
    button.addEventListener("click", () => {
        goalModal.style.display = "none";
        planModal.style.display = "none";
    });
});

// 提交目标表单
document.getElementById("goalForm").addEventListener("submit", function(event) {
    event.preventDefault();
    const formData = new FormData(this);

    fetch("{% url 'set_goal' %}", {
        method: "POST",
        body: JSON.stringify(Object.fromEntries(formData)),
        headers: {
            "X-CSRFToken": getCookie("csrftoken"),
            "Content-Type": "application/json"
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === "success") {
            document.getElementById("target-start").textContent = data.target_start_date;
            document.getElementById("target-end").textContent = data.target_end_date;
            document.getElementById("target-content").textContent = data.target;
            goalModal.style.display = "none";
        } else {
            alert("目标设置失败！");
        }
    })
    .catch(error => console.error("Error:", error));
});

// 提交计划表单
document.getElementById("planForm").addEventListener("submit", function(event) {
    event.preventDefault();
    const formData = new FormData(this);

    fetch("{% url 'set_plan' %}", {
        method: "POST",
        body: JSON.stringify(Object.fromEntries(formData)),
        headers: {
            "X-CSRFToken": getCookie("csrftoken"),
            "Content-Type": "application/json"
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === "success") {
            document.getElementById("user-plan").textContent = data.plan;
            planModal.style.display = "none";
        } else {
            alert("计划设置失败！");
        }
    })
    .catch(error => console.error("Error:", error));
});

// 获取 CSRF Token
function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== "") {
        let cookies = document.cookie.split(";");
        for (let i = 0; i < cookies.length; i++) {
            let cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + "=")) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
</script>